package com.hunanwenli.controller;

import com.hunanwenli.entity.UserInfo;
import com.hunanwenli.entity.UserPwd;
import com.hunanwenli.service.RedisService;
import com.hunanwenli.service.UserInfoService;
import com.hunanwenli.service.UserPwdService;
import com.hunanwenli.tool.Tools;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author wanzhenyu
 * @date 2021/5/26 22:08
 */
@Controller
@RequestMapping(value = "/login")
public class LoginController {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private UserPwdService userPwdService;
    private static final Logger logger = Logger.getLogger(LoginController.class);
    @GetMapping(value = "/selectUserId/{phone}")
    @ResponseBody
    public Integer selectUserId(@PathVariable("phone") String phone){
        UserInfo userInfo = null;
        Integer id = null;
        String str = redisService.get(phone);
        if (!Tools.isNullOrEmpty(str)){
            userInfo = Tools.jsonToPojo(str, UserInfo.class);
            id = userInfo.getId();
            return id;
        }else{
                userInfo = userInfoService.selectByPhone(phone);
        }
          if (!Tools.isNullOrEmpty(userInfo)){
              String myuserinfo = Tools.objectToJson(userInfo);
              redisService.put(phone,myuserinfo);
              id = userInfo.getId();
              return id;
          }else {
              return null;
          }
    }

    @GetMapping(value = "/isTruePwd/{id}/{password}")
    @ResponseBody
    public boolean isTruePwd(@PathVariable("id") Integer id,@PathVariable("password") String password){
        UserPwd userPwd = userPwdService.selectByPrimaryKey(id);
        String mypassword = userPwd.getPassword();
        String md5pw = Tools.getMD5(password);
        return md5pw.equals(mypassword);
    }

    @GetMapping(value = "/getUserInfoById/{uid}")
    @ResponseBody
    public UserInfo getUserInfoById(@PathVariable("uid") Integer uid){
        return userInfoService.selectByPrimaryKey(uid);
    }


    @GetMapping(value = "/getRedisUserInfo/{uuid}")
    @ResponseBody
   public UserInfo getRedisUserInfo(@PathVariable("uuid") String uuid){
        String userInfoJson = redisService.get(uuid);
        if(userInfoJson==null){
            return null;
        }else {
            return Tools.jsonToPojo(userInfoJson, UserInfo.class);
        }
    }
}
